
import bluetooth.*;
import Logika.*;
import java.util.Vector;
import javax.swing.JFrame;
import telebim.*;

/**
 *
 * @author pmp
 */
public class Main implements ServerListener, SendToAllListener {

    private Vector<String> clientAdres = new Vector<String>();
    private Server server;
    private String adress;
    private JFrame display;
    private int aktualnieObslugiwany;
    private MindServer serverGry = new MindServer(this);
    MainWindow mW;
    private int whichPlayer = 0; // indicate which player is connected to the server
    private int[] newTankPosition = new int[3];
    private Register register = new Register();

    /**
     * 
     */
    public Main() {
        display = new JFrame("publiczny wyswietlacz");
        server = new Server();
        server.createServer(this);
        server.publishServer();


        serverGry.uruchomWatekZyc();
        mW = new MainWindow();
        mW.plansza.setMap(serverGry.rozkladPlansza);
        mW.plansza.setTankInfo(register.registerInt);
        serverGry.setMW(mW);
    }

    public void clientConnected(String btAdress) {

        whichPlayer = register.add(btAdress);
        newTankPosition = serverGry.getNewTankPosition();
        clientAdres.addElement(btAdress);
        serverGry.setTank(newTankPosition[0], newTankPosition[1],
                newTankPosition[2], whichPlayer,
                btAdress);// W tym miejscu mozna podac polozenia Tank, lub przeslac z klienta
        sendToAll(serverGry.getStoredRozlad() + (char) newTankPosition[0] +
                (char) newTankPosition[1] + (char) newTankPosition[2] +
                (char) whichPlayer);

    }

    public void connectionLost(String btAdress) {
        serverGry.remove(btAdress);
        register.remove(btAdress);
        sendToAll(serverGry.getStoredRozlad());
    }

    public synchronized void dataReceived(String data, final String btAdress) {
        if (!serverGry.deadPlayers[clientAdres.indexOf(btAdress)]) {
            String komunikat = "";
            if ((int) data.charAt(0) == Zmienne.FIRE) {
                serverGry.uruchomWatekStrzalu(clientAdres.indexOf(btAdress), btAdress);
            } else {
                if (!(komunikat = serverGry.move(data, btAdress)).equals("")) {
                    if (komunikat.length() == 6) {
                        mW.plansza.moveTank(komunikat.charAt(0), komunikat.charAt(1), komunikat.charAt(3), komunikat.charAt(4));
                    }
                    sendToAll(komunikat);
                }
            }
        }
    }

    public void sendToAll(String komunikat) {
        for (int i = 0; i < serverGry.size(); i++) {
            server.sendData(komunikat, serverGry.elementAt(i));
        }
    }

    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        new Main();
    }
}
